<template>
  <div class="order-management">
    <!-- 页面标题和统计卡片 -->
    <lay-card>
      <template #header>
        <div class="page-header">
          <h2>订单管理</h2>
          <p>管理系统中的所有订单信息</p>
        </div>
      </template>
      <div class="stats-cards">
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ orderStats.totalOrders }}</div>
            <div class="stats-label">总订单数</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ orderStats.pendingPayment }}</div>
            <div class="stats-label">待付款</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ orderStats.pendingShipment }}</div>
            <div class="stats-label">待发货</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ orderStats.pendingReceipt }}</div>
            <div class="stats-label">待收货</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ orderStats.completed }}</div>
            <div class="stats-label">已完成</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ formatAmount(orderStats.totalAmount) }}</div>
            <div class="stats-label">总金额</div>
          </div>
        </lay-card>
      </div>
    </lay-card>

    <!-- 搜索筛选区域 -->
    <lay-card style="margin-top: 16px;">
      <lay-form :model="searchForm" ref="searchFormRef">
        <lay-row :space="16">
          <lay-col :md="6">
            <lay-form-item label="订单状态" prop="orderStatus">
              <lay-select v-model="searchForm.orderStatus" placeholder="请选择订单状态">
                <lay-select-option value="">全部</lay-select-option>
                <lay-select-option value="1">待付款</lay-select-option>
                <lay-select-option value="2">待发货</lay-select-option>
                <lay-select-option value="3">待收货</lay-select-option>
                <lay-select-option value="4">已完成</lay-select-option>
                <lay-select-option value="5">已取消</lay-select-option>
                <lay-select-option value="6">退款中</lay-select-option>
              </lay-select>
            </lay-form-item>
          </lay-col>
          <lay-col :md="6">
            <lay-form-item label="支付状态" prop="paymentStatus">
              <lay-select v-model="searchForm.paymentStatus" placeholder="请选择支付状态">
                <lay-select-option value="">全部</lay-select-option>
                <lay-select-option value="0">未支付</lay-select-option>
                <lay-select-option value="1">已支付</lay-select-option>
              </lay-select>
            </lay-form-item>
          </lay-col>
          <lay-col :md="6">
            <lay-form-item label="物流状态" prop="shippingStatus">
              <lay-select v-model="searchForm.shippingStatus" placeholder="请选择物流状态">
                <lay-select-option value="">全部</lay-select-option>
                <lay-select-option value="0">未发货</lay-select-option>
                <lay-select-option value="1">已发货</lay-select-option>
                <lay-select-option value="2">已收货</lay-select-option>
              </lay-select>
            </lay-form-item>
          </lay-col>
          <lay-col :md="6">
            <lay-form-item label="支付方式" prop="paymentMethod">
              <lay-select v-model="searchForm.paymentMethod" placeholder="请选择支付方式">
                <lay-select-option value="">全部</lay-select-option>
                <lay-select-option value="1">支付宝</lay-select-option>
                <lay-select-option value="2">微信</lay-select-option>
                <lay-select-option value="3">银行卡</lay-select-option>
              </lay-select>
            </lay-form-item>
          </lay-col>
        </lay-row>
        <lay-row :space="16">
          <lay-col :md="24">
            <lay-form-item>
              <lay-button type="primary" @click="handleSearch">
                <lay-icon type="layui-icon-search"></lay-icon>
                搜索
              </lay-button>
              <lay-button @click="handleReset" style="margin-left: 8px;">
                <lay-icon type="layui-icon-refresh"></lay-icon>
                重置
              </lay-button>
            </lay-form-item>
          </lay-col>
        </lay-row>
      </lay-form>
    </lay-card>

    <!-- 订单列表 -->
    <lay-card style="margin-top: 16px;">
      <lay-table 
        :columns="columns" 
        :data-source="tableData"
        :loading="loading"
        :default-toolbar="true"
        :pagination="false"
      >
        <template #orderNo="{ row }">
          <div class="order-no">
            <span class="order-text">{{ row.orderNo }}</span>
            <lay-button 
              type="primary" 
              size="xs" 
              @click="handleCopyOrderNo(row.orderNo)"
              style="margin-left: 8px;"
            >
              复制
            </lay-button>
          </div>
        </template>

        <template #orderStatus="{ row }">
          <lay-tag :type="getOrderStatusType(row.orderStatus)">
            {{ getOrderStatusText(row.orderStatus) }}
          </lay-tag>
        </template>

        <template #paymentStatus="{ row }">
          <lay-tag :type="row.paymentStatus === 1 ? 'normal' : 'warm'">
            {{ row.paymentStatus === 1 ? '已支付' : '未支付' }}
          </lay-tag>
        </template>

        <template #shippingStatus="{ row }">
          <lay-tag :type="getShippingStatusType(row.shippingStatus)">
            {{ getShippingStatusText(row.shippingStatus) }}
          </lay-tag>
        </template>

        <template #consignee="{ row }">
          <div class="consignee-info">
            <div>{{ row.consigneeName }}</div>
            <div class="phone">{{ row.consigneePhone }}</div>
          </div>
        </template>

        <template #amount="{ row }">
          <div class="amount-info">
            <div class="total-amount">¥{{ formatAmount(row.totalAmount) }}</div>
            <div class="goods-amount">商品: ¥{{ formatAmount(row.goodsAmount) }}</div>
            <div class="shipping-fee" v-if="row.shippingFee > 0">运费: ¥{{ formatAmount(row.shippingFee) }}</div>
          </div>
        </template>

        <template #createdAt="{ row }">
          {{ formatDateTime(row.createdAt) }}
        </template>

        <template #action="{ row }">
          <div class="action-buttons">
            <lay-button type="primary" size="xs" @click="handleViewDetail(row)">
              详情
            </lay-button>
            <lay-button 
              v-if="row.orderStatus === 2 && row.paymentStatus === 1" 
              type="normal" 
              size="xs" 
              @click="handleShip(row)"
            >
              发货
            </lay-button>
            <lay-button 
              v-if="row.orderStatus === 1" 
              type="warm" 
              size="xs" 
              @click="handleCancel(row)"
            >
              取消
            </lay-button>
            <!-- <lay-dropdown>
              <lay-button size="xs">
                更多
                <lay-icon type="layui-icon-down"></lay-icon>
              </lay-button>
              <template #content>
                <lay-dropdown-menu>
                  <lay-dropdown-menu-item @click="handleRemark(row)">备注</lay-dropdown-menu-item>
                </lay-dropdown-menu>
              </template>
            </lay-dropdown> -->
          </div>
        </template>
      </lay-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <lay-page 
          v-model="pagination.current"
          v-model:limit="pagination.pageSize"
          :total="pagination.total"
          :show-total="true"
          :show-jumper="true"
          :show-limit="true"
          :limits="pagination.limits"
          @change="handlePageChange"
        />
      </div>
    </lay-card>

    <!-- 订单详情对话框 -->
    <OrderDetailDialog 
      v-model:visible="detailDialogVisible"
      :order-id="selectedOrderId"
      @refresh="getOrderList"
    />

    <!-- 发货对话框 -->
    <ShipmentDialog 
      v-model:visible="shipmentDialogVisible"
      :order="selectedOrder"
      @refresh="getOrderList"
    />

    <!-- 备注对话框 -->
    <RemarkDialog 
      v-model:visible="remarkDialogVisible"
      :order="selectedOrder"
      @refresh="getOrderList"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { layer } from '@layui/layer-vue'
import { orderApi, type Order, type OrderQueryParams, OrderStatus, PaymentStatus, ShippingStatus } from '@/api/module/order'
import OrderDetailDialog from './components/OrderDetailDialog.vue'
import ShipmentDialog from './components/ShipmentDialog.vue'
import RemarkDialog from './components/RemarkDialog.vue'

// 响应式数据
const loading = ref(false)
const tableData = ref<Order[]>([])
const detailDialogVisible = ref(false)
const shipmentDialogVisible = ref(false)
const remarkDialogVisible = ref(false)
const selectedOrderId = ref<number | null>(null)
const selectedOrder = ref<Order | null>(null)

// 订单统计数据
const orderStats = ref({
  totalOrders: 0,
  pendingPayment: 0,
  pendingShipment: 0,
  pendingReceipt: 0,
  completed: 0,
  cancelled: 0,
  refunding: 0,
  totalAmount: 0,
  todayOrders: 0,
  todayAmount: 0
})

// 搜索表单
const searchForm = reactive({
  keyword: '',
  orderStatus: '',
  paymentStatus: '',
  shippingStatus: '',
  paymentMethod: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  limits: [10, 20, 50, 100]
})

// 表格列配置
const columns = [
  {
    title: '订单号',
    key: 'orderNo',
    customSlot: 'orderNo',
    width: 200,
    fixed: 'left'
  },
  {
    title: '订单状态',
    key: 'orderStatus',
    customSlot: 'orderStatus',
    width: 100
  },
  {
    title: '支付状态',
    key: 'paymentStatus',
    customSlot: 'paymentStatus',
    width: 100
  },
  {
    title: '物流状态',
    key: 'shippingStatus',
    customSlot: 'shippingStatus',
    width: 100
  },
  {
    title: '收货人信息',
    key: 'consignee',
    customSlot: 'consignee',
    width: 150
  },
  {
    title: '金额信息',
    key: 'amount',
    customSlot: 'amount',
    width: 150
  },
  {
    title: '创建时间',
    key: 'createdAt',
    customSlot: 'createdAt',
    width: 160
  },
  {
    title: '操作',
    key: 'action',
    customSlot: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 获取订单列表
const getOrderList = async () => {
  try {
    loading.value = true
    const params: OrderQueryParams = {
      page: pagination.current,
      limit: pagination.pageSize,
      orderNo: searchForm.keyword || undefined,
      orderStatus: searchForm.orderStatus ? Number(searchForm.orderStatus) as OrderStatus : undefined,
      paymentStatus: searchForm.paymentStatus ? Number(searchForm.paymentStatus) as PaymentStatus : undefined,
      shippingStatus: searchForm.shippingStatus ? Number(searchForm.shippingStatus) as ShippingStatus : undefined,
      consigneeName: searchForm.keyword || undefined,
      consigneePhone: searchForm.keyword || undefined
    }

    const response = await orderApi.getOrderList(params)
    if (response.code === 200) {
      tableData.value = response.data.list
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    layer.msg('获取订单列表失败', { icon: 2 })
  } finally {
    loading.value = false
  }
}

// 获取订单统计
const getOrderStats = async () => {
  try {
    const response = await orderApi.getOrderStats()
    if (response.code === 200) {
      orderStats.value = response.data
    }
  } catch (error) {
    console.error('获取订单统计失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getOrderList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    orderStatus: '',
    paymentStatus: '',
    shippingStatus: '',
    paymentMethod: ''
  })
  pagination.current = 1
  getOrderList()
}

// 刷新
const handleRefresh = () => {
  getOrderList()
  getOrderStats()
}

// 分页变化
const handlePageChange = ({ current, limit }: { current: number; limit: number }) => {
  pagination.current = current
  pagination.pageSize = limit
  getOrderList()
}

// 查看详情
const handleViewDetail = (order: Order) => {
  selectedOrderId.value = order.id
  detailDialogVisible.value = true
}

// 发货
const handleShip = (order: Order) => {
  selectedOrder.value = order
  shipmentDialogVisible.value = true
}

// 取消订单
const handleCancel = async (order: Order) => {
  try {
    const confirm = await layer.confirm('确定要取消这个订单吗？', {
      title: '确认取消',
      icon: 3
    })
    
    if (confirm) {
      const response = await orderApi.cancelOrder(order.id)
      if (response.code === 200) {
        layer.msg('订单取消成功', { icon: 1 })
        getOrderList()
        getOrderStats()
      }
    }
  } catch (error) {
    console.error('取消订单失败:', error)
    layer.msg('取消订单失败', { icon: 2 })
  }
}

// 编辑订单 - 已注释，管理员不可编辑订单
// const handleEdit = (order: Order) => {
//   // TODO: 实现编辑功能
//   layer.msg('编辑功能开发中', { icon: 0 })
// }

// 打印订单
const handlePrint = (order: Order) => {
  // TODO: 实现打印功能
  layer.msg('打印功能开发中', { icon: 0 })
}

// 备注
const handleRemark = (order: Order) => {
  selectedOrder.value = order
  remarkDialogVisible.value = true
}


// 复制订单号
const handleCopyOrderNo = async (orderNo: string) => {
  try {
    await navigator.clipboard.writeText(orderNo)
    layer.msg('订单号已复制', { icon: 1 })
  } catch (error) {
    layer.msg('复制失败', { icon: 2 })
  }
}

// 格式化金额
const formatAmount = (amount: number | string) => {
  const numAmount = typeof amount === 'string' ? parseFloat(amount) : amount
  return numAmount?.toFixed(2) || '0.00'
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取订单状态类型
const getOrderStatusType = (status: number) => {
  const statusMap = {
    1: 'warm',     // 待付款
    2: 'normal',   // 待发货
    3: 'primary',  // 待收货
    4: 'normal',   // 已完成
    5: 'danger',   // 已取消
    6: 'warm'      // 退款中
  }
  return statusMap[status] || 'primary'
}

// 获取订单状态文本
const getOrderStatusText = (status: number) => {
  const statusMap = {
    1: '待付款',
    2: '待发货',
    3: '待收货',
    4: '已完成',
    5: '已取消',
    6: '退款中'
  }
  return statusMap[status] || '未知'
}

// 获取物流状态类型
const getShippingStatusType = (status: number) => {
  const statusMap = {
    0: 'warm',     // 未发货
    1: 'primary',  // 已发货
    2: 'normal'    // 已收货
  }
  return statusMap[status] || 'primary'
}

// 获取物流状态文本
const getShippingStatusText = (status: number) => {
  const statusMap = {
    0: '未发货',
    1: '已发货',
    2: '已收货'
  }
  return statusMap[status] || '未知'
}

// 页面加载
onMounted(() => {
  getOrderList()
  getOrderStats()
})
</script>

<style scoped>
.order-management {
  padding: 16px;
}

.page-header {
  margin-bottom: 16px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.stats-card {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  transition: all 0.3s ease;
  height: 120px;
  display: flex;
  align-items: center;
}

.stats-card:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

.stats-content {
  text-align: center;
  padding: 20px;
  width: 100%;
}

.stats-number {
  font-size: 28px;
  font-weight: 600;
  color: #1890ff;
  margin-bottom: 8px;
  line-height: 1.2;
  word-break: break-word;
}

.stats-label {
  font-size: 14px;
  color: #666;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.toolbar-left {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.toolbar-right {
  display: flex;
  gap: 8px;
  align-items: center;
}

.order-no {
  display: flex;
  align-items: center;
}

.order-text {
  font-family: monospace;
  font-weight: 500;
}

.consignee-info {
  line-height: 1.4;
}

.phone {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.amount-info {
  line-height: 1.4;
}

.total-amount {
  font-weight: 600;
  color: #f56c6c;
}

.goods-amount,
.shipping-fee {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

.action-buttons {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .toolbar-right {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>